Longest Palindromic Substring

Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring.

Solution:

  1. public class Solution {
  2. public String longestPalindrome(String s) {
  3. int n = s.length();
  4. String res = null;
  5. boolean[][] dp = new boolean[n][n];
  6. for (int i = n - 1; i >= 0; i--) {
  7. for (int j = i; j < n; j++) {
  8. dp[i][j] = s.charAt(i) == s.charAt(j) && (j - i <= 2 || dp[i + 1][j - 1]);
  9. if (dp[i][j] && (res == null || j - i + 1 > res.length())) {
  10. res = s.substring(i, j + 1);
  11. }
  12. }
  13. }
  14. return res;
  15. }
  16. }